package cn.lg.soar.boot.fc.controller;

import cn.lg.soar.boot.client.entity.ClientUser;
import cn.lg.soar.boot.client.service.ClientUserService;
import cn.lg.soar.boot.fc.entity.Campus;
import cn.lg.soar.boot.fc.entity.TenancyRoomRecord;
import cn.lg.soar.boot.fc.entity.vo.FinanceExcelVo;
import cn.lg.soar.boot.fc.entity.vo.FinanceVo;
import cn.lg.soar.boot.fc.entity.vo.RoomVo;
import cn.lg.soar.boot.fc.entity.vo.TenancyRoomRecordVo;
import cn.lg.soar.boot.fc.service.RoomService;
import cn.lg.soar.common.data.msg.I18n;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.group.Create;
import cn.lg.soar.core.annotations.constraints.group.Update;
import cn.lg.soar.core.util.easyexcel.ExcelUtil;
import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.mvc.enums.ControllerConst;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.mvc.annotations.Log;
import cn.lg.soar.system.auth.entity.User;
import cn.lg.soar.system.auth.service.IUserService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.boot.fc.entity.Finance;
import cn.lg.soar.boot.fc.service.FinanceService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 财务表
 * @author ZhuanZ（无密码）
 * @since 2025-01-18
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Api(tags = "财务表")
@Validated
@RestController
@RequestMapping("fc/finance")
public class FinanceController extends BaseController<Finance, FinanceService> {

    @Resource
    private RoomService roomService;
    @Autowired
    protected IUserService userService;
    /** 客户端用户信息服务 */
    @Autowired private ClientUserService clientUserService;

    @Override
    protected Serializable getId(Finance entity) {
        return entity.getId();
    }

    @Log(value = "新增财务表", data = "#p0", dataId = "#$r.data")
    @IdempotentByParam("#p0")
    @ApiOperation(value = ControllerConst.CREATE_NAME)
    @RequestMapping(path = "create", method = RequestMethod.POST)
    public HttpResult<Serializable> create(@RequestBody @Validated(Create.class) Finance data) {
        return super.createResult(data);
    }

    @Log(value = "修改财务表", data = "#p0", dataId = "#p0.id")
    @ApiOperation(value = ControllerConst.UPDATE_NAME)
    @RequestMapping(path = "update", method = RequestMethod.POST)
    public HttpResult<Void> update(@RequestBody @Validated(Update.class) Finance data) {
        return super.updateResult(data);
    }

    @Log(value = "删除财务表", data = "#p0")
    @ApiOperation(value = ControllerConst.REMOVE_NAME, notes = "根据 id 删除")
    @RequestMapping(path = "remove", method = RequestMethod.POST)
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        return super.removeResult(ids);
    }

    @ApiOperation(value = ControllerConst.DETAIL_NAME, notes = "根据 ID 获取一条数据")
    @RequestMapping(path = "detail", method = RequestMethod.GET)
    public HttpResult<FinanceVo> detail(@RequestParam Long id) {
        Finance record = super.detailResult(id).getData();
        FinanceVo vo = new FinanceVo();
        BeanUtils.copyProperties(record, vo);
        if(record.getRoomId() != null){
            RoomVo roomVo = roomService.getVoData(record.getRoomId());
            String roomInfo = "";
            if(roomVo != null) {
                roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                        +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
            }
            vo.setRoomInfo(roomInfo);
            vo.setArea(roomVo.getArea());
            vo.setLivingRoom(roomVo.getLivingRoom());
            vo.setOrient(roomVo.getOrient());
            vo.setOwnershipCode(roomVo.getOwnershipCode());
            vo.setContacts(roomVo.getContacts());
            vo.setPhone(roomVo.getPhone());
        }

//        User user = userService.getById(record.getUserId());
//        if(user != null) {
//            vo.setUserName(user.getNickname());
//        }
        ClientUser user = clientUserService.getById(record.getUserId());
        if(user != null) {
            vo.setUserName(user.getUserName());
        }
        return HttpResult.data(vo);
    }

    @ApiOperation(value = ControllerConst.QUERY_NAME, notes = "多功能查询（分页、列表、统计）")
    @RequestMapping(path = "query", method = RequestMethod.GET)
    public HttpResult<PageResult<FinanceVo>> query(PageQuery pageQuery, QueryParams params){
        params.setFields(new ArrayList<>());
        PageResult<FinanceVo> pageResult = new PageResult<>();
        List<FinanceVo> list = new ArrayList<>();
        List<Finance> recordQuery = super.queryResult(pageQuery, params).getData().getList();
        for (Finance record : recordQuery) {
            FinanceVo vo = new FinanceVo();
            BeanUtils.copyProperties(record, vo);
            if(record.getRoomId() != null){
                RoomVo roomVo = roomService.getVoData(record.getRoomId());
                String roomInfo = "";
                if(roomVo != null) {
                    roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                            +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
                }
                vo.setRoomInfo(roomInfo);
                vo.setArea(roomVo.getArea());
                vo.setLivingRoom(roomVo.getLivingRoom());
                vo.setOrient(roomVo.getOrient());
                vo.setOwnershipCode(roomVo.getOwnershipCode());
                vo.setContacts(roomVo.getContacts());
                vo.setPhone(roomVo.getPhone());
            }

//            User user = userService.getById(record.getUserId());
//            if(user != null) {
//                vo.setUserName(user.getNickname());
//            }
            ClientUser user = clientUserService.getById(record.getUserId());
            if(user != null) {
                vo.setUserName(user.getUserName());
            }
            list.add(vo);
        }
        pageResult.setList(list);
        return HttpResult.data(pageResult);
    }

    private SqueryWapper<Finance> squeryWapper;
    @Log(value = "导出财务表")
    @ApiOperation(value = ControllerConst.EXPORT_NAME)
    @RequestMapping(path = "export", method = RequestMethod.GET)
    public void exports(QueryParams params, HttpServletResponse resp){
        List<Finance> list = new ArrayList<>();
        if(params.getFields() != null){
            params.setFields(new ArrayList<>());
            list = super.getList(params);
        }
        super.service.exports(list,resp);
    }

    @Log(value = "导入财务表")
    @ApiOperation(value = ControllerConst.IMPORT_NAME)
    @RequestMapping(path = "import", method = RequestMethod.POST)
    public HttpResult<Void> imports(@RequestParam MultipartFile files){
        return super.service.imports(files);
    }

    @Log(value = "账单缴费", data = "#p0", dataId = "#p0.id")
    @ApiOperation(value = "账单缴费")
    @RequestMapping(path = "billPayment", method = RequestMethod.POST)
    public HttpResult<Void> billPayment(@RequestBody Finance data) {
        return super.service.billPayment(data);
    }

    @Log(value = "生成账单", data = "#p0", dataId = "#$r.data")
    @ApiOperation(value = "生成账单")
    @RequestMapping(path = "generateBill", method = RequestMethod.POST)
    public HttpResult<Void> generateBill(@RequestBody Finance data) {
        return super.service.generateBill(data);
    }

}